package com.gomoney.auth.controller;

import com.gomoney.auth.common.util.JwtUtil;
import com.gomoney.auth.common.util.RedisUtil;
import com.gomoney.auth.service.SysCaptchaService;
import com.gomoney.auth.common.util.JwtUtil;
import com.gomoney.auth.common.util.RedisUtil;
import com.gomoney.auth.service.SysCaptchaService;
import com.gomoney.auth.service.SysUserService;
import com.gomoney.oauth2.common.entity.sys.SysUser;
import com.gomoney.oauth2.common.form.sys.LoginForm;
import com.gomoney.oauth2.common.util.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * Created by admin on 2018/6/25.
 */
@RestController
@RequestMapping("/sys/authentication")
@Api("授权管理")
public class PremessionController extends AbstractController {

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private SysUserService userService;

    @Autowired
    private SysCaptchaService sysCaptchaService;


    @Autowired
    private PasswordEncoder passwordEncoder;

    @ApiOperation("验证码")
    @GetMapping("captcha.jpg")
    public void captcha(String uuid) throws IOException {
        RequestAttributes ra = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes sra = (ServletRequestAttributes) ra;
        sra.getResponse().setHeader("Cache-Control", "no-store, no-cache");
        sra.getResponse().setContentType("image/jpeg");
        BufferedImage image = sysCaptchaService.getCaptcha(uuid);
        ServletOutputStream out = sra.getResponse().getOutputStream();
        ImageIO.write(image, "jpg", out);
        IOUtils.close(out);
    }

    @ApiOperation(notes = "登陆", value = "com.gomoney.common.form.sys.LoginForm")
    @PostMapping("/require")
    public R login(@RequestBody LoginForm user) {
        boolean captcha = sysCaptchaService.validate(user.getUuid(), user.getCaptcha());
        if (!captcha) {
            return R.error("验证码不正确");
        }
        SysUser sysUser = userService.login(user.getUsername());
        if (sysUser != null && sysUser.getState() == 0) {
            return R.error("账号被冻结");
        } else if (sysUser != null && sysUser.getState() == -1) {
            return R.error("账号被注销");
        } else if (sysUser != null && passwordEncoder.matches(user.getPassword(), sysUser.getUserPass())) {
            return userService.createToken(sysUser.getUserId());
        } else {
            return R.error("账号或密码不正确");
        }
    }

    @ApiOperation("登出")
    @PostMapping("/logout")
    public R logout() {
        String token = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getHeader("Authorization");
        redisUtil.del(token);
        token = "oauth:jwt:" + token.replaceAll("bearer ", "");
        redisUtil.del(token);
        token = "oauth:jwt:refresh:" + token.replaceAll("bearer ", "");
        redisUtil.del(token);
        return R.ok();
    }

    @ApiOperation("获取刷新token")
    @PostMapping("/refreshToken")
    public R refreshToken() {
        String token = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getHeader("Authorization");
        token = "oauth:jwt:refresh:" + token.replaceAll("bearer ", "");
        if(redisUtil.get(token)!=null){
            token = redisUtil.get(token).toString();
        }
        return R.ok().put("refresh_token", token);
    }
}
